<template>
  <view class="page">
    <!-- 页面顶部 -->
    <view class="header">
      <view class="title">我的收藏</view>
      <view v-if="favorites.length > 0" class="count">{{ favorites.length }}</view>
    </view>

    <!-- 空状态 -->
    <view v-if="favorites.length === 0" class="empty">
      <view class="empty-icon">
        <uni-icons type="heart" color="#D1D5DB" :size="64" />
      </view>
      <view class="empty-title">还没有收藏菜品</view>
      <view class="empty-desc">收藏喜欢的菜品，方便以后快速查找</view>
      <button class="go-shop" @click="goToShop">去挑选菜品</button>
    </view>

    <!-- 收藏列表 -->
    <view v-else class="favorites-list">
      <view class="item" v-for="fav in favorites" :key="fav._id">
        <!-- 菜品图片 -->
        <view class="item-image-wrapper">
          <image class="item-image" :src="getImageSrc(fav.dish_image)" mode="aspectFill" />
          <view class="delete-btn" @click.stop="removeFavorite(fav)">
            <uni-icons type="trash" color="#EF4444" :size="20" />
          </view>
        </view>

        <!-- 菜品信息 -->
        <view class="item-info">
          <view class="item-header">
            <view class="item-name">{{ fav.dish_name }}</view>
            <view class="item-category">{{ fav.category_name }}</view>
          </view>

          <!-- 菜品标签 -->
          <view class="item-tags">
            <view class="tag spiciness" :class="getSpicinessClass(fav.dish_spiciness)">
              {{ getSpicinessText(fav.dish_spiciness) }}
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="item-actions">
            <button class="btn secondary" @click="viewDetail(fav)">查看详情</button>
            <button class="btn primary" @click="addToCart(fav)">
              <uni-icons type="cart" color="#fff" :size="18" />
              <text>加入已点</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="favorites.length < total" class="load-more">
        <button class="load-btn" @click="loadMore">加载更多</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getImageSrc } from '@/common/image.js'
import { getSpicinessText, getSpicinessClass } from '@/common/dish.js'
import cart from '@/common/cart.js'

const favorites = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = 20
const loading = ref(false)

// 加载收藏列表
const loadFavorites = async (loadMore = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    // 获取 uid
    let uid = null
    try {
      const userInfo = uniCloud.getCurrentUserInfo()
      if (userInfo && userInfo.uid) {
        uid = userInfo.uid
      }
    } catch (e) {
      // 尝试从本地存储获取
      try {
        const userInfoStr = uni.getStorageSync('uni_id_user_info')
        if (userInfoStr) {
          const userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr
          uid = userInfo._id || userInfo.uid
        }
      } catch (e2) {
        // 都失败了
      }
    }
    
    if (!uid) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      loading.value = false
      return
    }

    const res = await uniCloud.callFunction({
      name: 'food-favorites',
      data: {
        action: 'get-favorites',
        data: {
          uid,
          page: page.value,
          pageSize: pageSize
        }
      }
    })

    if (res.result && res.result.code === 200) {
      const { list = [], total: totalCount = 0 } = res.result.data || {}
      
      if (loadMore) {
        favorites.value = [...favorites.value, ...list]
      } else {
        favorites.value = list
      }
      
      total.value = totalCount
    } else {
      uni.showToast({
        title: res.result?.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (err) {
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 删除收藏
const removeFavorite = (fav) => {
  uni.showModal({
    title: '删除收藏',
    content: `确定删除 "${fav.dish_name}" 的收藏吗？`,
    async success(res) {
      if (res.confirm) {
        try {
          // 获取 uid
          let uid = null
          try {
            const userInfo = uniCloud.getCurrentUserInfo()
            if (userInfo && userInfo.uid) {
              uid = userInfo.uid
            }
          } catch (e) {
            // 尝试从本地存储获取
            try {
              const userInfoStr = uni.getStorageSync('uni_id_user_info')
              if (userInfoStr) {
                const userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr
                uid = userInfo._id || userInfo.uid
              }
            } catch (e2) {
              // 都失败了
            }
          }

          if (!uid) {
            uni.showToast({
              title: '请先登录',
              icon: 'none'
            })
            return
          }

          const removeRes = await uniCloud.callFunction({
            name: 'food-favorites',
            data: {
              action: 'remove-favorite',
              data: {
                uid,
                favorite_id: fav._id
              }
            }
          })

          if (removeRes.result && removeRes.result.code === 200) {
            uni.showToast({
              title: '已删除',
              icon: 'success'
            })
            // 从列表中移除
            favorites.value = favorites.value.filter(item => item._id !== fav._id)
            total.value -= 1
          } else {
            uni.showToast({
              title: removeRes.result?.message || '删除失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 加入已点
const addToCart = (fav) => {
  try {
    // 需要构建包含 _id 字段的菜品对象，因为 cart.addItem 会检查 dish._id
    const dish = {
      _id: fav.dish_id,  // cart.addItem 需要 _id 字段
      id: fav.dish_id,
      name: fav.dish_name,
      image: fav.dish_image
    }
    
    const result = cart.addItem(dish, 1)
    
    if (result && Array.isArray(result)) {
      cart.syncTabBadge(2)
      
      uni.showToast({
        title: '已加入已点',
        icon: 'success'
      })
    } else {
      throw new Error('添加失败')
    }
  } catch (err) {
    uni.showToast({
      title: '加入失败',
      icon: 'none'
    })
  }
}

// 查看详情
const viewDetail = (fav) => {
  uni.navigateTo({
    url: `/pages/dish-detail/dish-detail?id=${fav.dish_id}`
  })
}

// 加载更多
const loadMore = () => {
  page.value += 1
  loadFavorites(true)
}

// 去购物
const goToShop = () => {
  uni.switchTab({
    url: '/pages/category/category'
  })
}

onMounted(() => {
  loadFavorites()
})

onShow(() => {
  // 每次进入页面都刷新收藏列表
  page.value = 1
  loadFavorites()
})
</script>

<style lang="scss" scoped>
$page-padding: 32rpx;
$radius-lg: 16rpx;
$border: 1rpx solid #eef2f7;
$text-muted: #6b7280;

.page {
  min-height: 100vh;
  background: #f8fafc;
  padding-bottom: 100rpx;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx $page-padding 24rpx;
  background: #ffffff;
  border-bottom: $border;

  .title {
    font-size: 36rpx;
    font-weight: 700;
    color: #0f172a;
  }

  .count {
    background: #ef4444;
    color: #ffffff;
    border-radius: 50%;
    width: 56rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: 600;
  }
}

.empty {
  padding: 120rpx $page-padding;
  text-align: center;

  .empty-icon {
    margin-bottom: 24rpx;
  }

  .empty-title {
    font-size: 32rpx;
    font-weight: 700;
    color: #0f172a;
    margin-bottom: 12rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: $text-muted;
    margin-bottom: 48rpx;
  }

  .go-shop {
    background: #10b981;
    color: #ffffff;
    border: none;
    border-radius: 12rpx;
    padding: 20rpx 36rpx;
    font-size: 28rpx;
  }
}

.favorites-list {
  padding: $page-padding;
  display: flex;
  flex-direction: column;
  gap: 24rpx;

  .item {
    background: #ffffff;
    border-radius: $radius-lg;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
    display: flex;
    gap: 20rpx;
  }

  .item-image-wrapper {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    flex-shrink: 0;

    .item-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .delete-btn {
      position: absolute;
      top: 8rpx;
      right: 8rpx;
      width: 48rpx;
      height: 48rpx;
      background: #ffffff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    }
  }

  .item-info {
    flex: 1;
    padding: 20rpx 0 20rpx 12rpx;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
  }

  .item-header {
    display: flex;
    flex-direction: column;
    gap: 8rpx;

    .item-name {
      font-size: 30rpx;
      font-weight: 700;
      color: #0f172a;
      line-height: 1.2;
    }

    .item-category {
      font-size: 24rpx;
      color: $text-muted;
    }
  }

  .item-tags {
    display: flex;
    gap: 8rpx;
    flex-wrap: wrap;

    .tag {
      padding: 4rpx 12rpx;
      font-size: 22rpx;
      border-radius: 8rpx;
      background: #f3f4f6;
      color: #6b7280;

      &.spiciness {
        &.lv0 { background: #dbeafe; color: #0284c7; }
        &.lv1 { background: #fef3c7; color: #d97706; }
        &.lv2 { background: #fed7aa; color: #d97706; }
        &.lv3 { background: #fed7aa; color: #dc2626; }
        &.lv4 { background: #fca5a5; color: #dc2626; }
      }
    }
  }

  .item-actions {
    display: flex;
    gap: 12rpx;
    margin-top: 8rpx;

    .btn {
      flex: 1;
      border: none;
      border-radius: 8rpx;
      padding: 12rpx 16rpx;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6rpx;
    }

    .btn.secondary {
      background: #eef2f7;
      color: #0f172a;
    }

    .btn.primary {
      background: #10b981;
      color: #ffffff;
    }
  }

  .load-more {
    text-align: center;
    padding: 24rpx 0;

    .load-btn {
      background: #f3f4f6;
      color: #6b7280;
      border: none;
      border-radius: 8rpx;
      padding: 16rpx 32rpx;
      font-size: 26rpx;
    }
  }
}
</style>
